package com.york.subject.domain.handler.subject;

import com.york.subject.common.enums.SubjectInfoTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目类型工厂
 * implements InitializingBean 为了初始化的时候加载
 */
@Component
public class SubjectTypeHandlerFactory implements InitializingBean {

    /**
     * 注入不同类型的Handler
     * 从容器中注入所有SubjectTypeHandler类型的bean到subjectTypeHandlerList中去
     * 所以SubjectTypeHandler要注入
     */
    @Resource
    private List<SubjectTypeHandler> subjectTypeHandlerList;

    // 装载工厂模式，有多种形式，这里用Map的方式，只需要用题目类型枚举就可以返回对应策略
    private Map<SubjectInfoTypeEnum, SubjectTypeHandler> handlerMap = new HashMap<>();

    /**
     * 得到Map中存储的Handler
     */
    public SubjectTypeHandler getHandler(int subjectType) {
        // 得到HashMap的key然后返回即可
        SubjectInfoTypeEnum subjectInfoTypeEnum = SubjectInfoTypeEnum.getByCode(subjectType);
        return handlerMap.get(subjectInfoTypeEnum);
    }


    /**
     * 初始化以后把Handler先注入到Map中，哪里要用就get
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SubjectTypeHandler subjectTypeHandler : subjectTypeHandlerList) {
            handlerMap.put(subjectTypeHandler.getHandlerType(), subjectTypeHandler);
        }
    }
}
